package com.zxj.geekstudy.other.proxy.cglib;

import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class SampleClass {

    public void test(){
        System.out.println("hello world");
    }

    public void test1(){
        System.out.println("hello world1");
    }

    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(SampleClass.class);
        MethodInterceptor interceptor = new MethodInterceptor() {
            @Override
            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
                System.out.println("before method run...");
                Object result = proxy.invokeSuper(obj, args);
                System.out.println("after method run...");
                return result;
            }
        };
        MethodInterceptor interceptor1 = new MethodInterceptor() {
            @Override
            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
                System.out.println("before method run1...");
//                method.invoke(new SampleClass(), args);
//                proxy.invoke(new SampleClass(), args);
                Object result = proxy.invokeSuper(obj, args);
                System.out.println("after method run1...");
                return result;
            }
        };
        enhancer.setCallbackFilter((method) ->{
            String methodName = method.getName();
            if ("test".equals(methodName)) {
                return 0; // eat()方法使用callbacks[1]对象拦截。
            }
            return 1;   //其他方法使用callbacks[0]对象拦截。
        });
        enhancer.setCallbacks(new Callback[]{interceptor, interceptor1});
        SampleClass sample = (SampleClass) enhancer.create();
//        sample.test();
//        sample.test1();
        Method[] methods = SampleClass.class.getMethods();
        for (Method method : methods) {
            if (method.getName().contains("test")) {
                method.invoke(sample, null);
            }
        }
    }
}
